/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.spring.authorizationserver.configuration;

import lombok.RequiredArgsConstructor;
import org.elsfs.cloud.common.properties.ElsfsSecurityProperties;
import org.elsfs.cloud.spring.common.config.CustomSecurityConfigurer;
import org.elsfs.cloud.spring.common.configurer.AbstractSecurityCustomConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
import org.springframework.security.web.SecurityFilterChain;

/**
 * security 配置
 *
 * @author zeng
 */
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(ElsfsSecurityProperties.class)
public class SecurityAutoConfiguration extends AbstractSecurityCustomConfiguration {
  @Bean
  @Order(2)
  SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
    // 禁用csrf
    http.csrf(CsrfConfigurer::disable);
    // 配置认证的请求
    addHttpSecurityAuthorizeHttpRequests(http);
    // 配置自定义登录页面
    http.formLogin(login -> login.loginPage("/login"));
    // 配置认证jwt
    http.oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()));
    // 配置密码管理
    http.passwordManagement(Customizer.withDefaults());
    // 配置响应头
    addHttpSecurityHeaders(http);
    // 配置oauth2 登录
    autoConfigurationOauthLogin(http);
    // 配置自定义过滤器链
    CustomSecurityConfigurer.applyDefaultSecurity(http);
    return http.build();
    // @formatter:on
  }

  @Override
  public void afterPropertiesSet() throws Exception {}
}
